/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.ArrayList;

/**
 *
 * @author alocubiche
 */
public class Panier {
    private ArrayList<Item> articles;
    
    public Panier(){
        articles= new ArrayList<Item>();
    }
    
    public ArrayList<Item> getArticles() {
        System.out.println(articles.size() + " articles dans le panier");
        return articles;
    }

    public void setArticles(ArrayList<Item> articles) {
        this.articles = articles;
    }
    
    public void addItem(Item item){
        articles.add(item);
        if (MySQLManager.connect())
        {
            PreparedStatement pstmt = null;
            try {
                Connection conn = MySQLManager.getConnection();
                pstmt = conn.prepareStatement("UPDATE item SET available = available - " + item.getQuantity() + " WHERE id = " + item.getId());
                pstmt.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }
            MySQLManager.disconnect();
        }
    }
    
    public void removeItem(Item item){
        for(int i = 0; i < articles.size(); i++)
        {
            if (articles.get(i).getId() == item.getId()){
               articles.remove(i);
            }
        }
        if (MySQLManager.connect())
        {
            PreparedStatement pstmt = null;
            try {
                Connection conn = MySQLManager.getConnection();
                pstmt = conn.prepareStatement("UPDATE item SET available = available + " + item.getQuantity() + " WHERE id = " + item.getId());
                pstmt.executeUpdate();
            } catch (Exception e) {
                e.printStackTrace();
            }
            MySQLManager.disconnect();
        }
    }
    
    public float totalAmount(){
        float amount = 0;
        for(Item article : articles)
        {
            amount = amount + (article.getPrice() * article.getQuantity());
        }
        return amount;
    }
    public int numberArticle(){
        int nb = 0;
        for(Item article : articles)
        {
            nb = nb + article.getQuantity();
        }
        return nb;
    }
    
    
}
